/*****************************************************************************/
/* FILE NAME: spi.c                   COPYRIGHT (c) NXP Semiconductors 2015  */
/*                                                      All Rights Reserved  */
/* PLATFORM: DEVKIT-MPC5748G												 */
/* DESCRIPTION: SPI functions for initialization and reading received data.  */
/*                                                                           */
/*****************************************************************************/	
/* REV      AUTHOR        DATE        DESCRIPTION OF CHANGE                  */
/* ---   -----------    ----------    ---------------------                  */
/* 1.0	 Scott Obrien   29 Apr 2015   Initial Version                        */
/* 1.1		K Shah		16 Mar 2016   Ported to S32DS						 */
/*****************************************************************************/

#include "project.h"
#include "spi.h"

#define SPI_FMSZ(x)	((x)<<(27))
#define SPI_CPOL(x)	((x)<<(26))
#define SPI_CPHA(x)	((x)<<(25))

/*
 * PJ[2]		817	0000_0010	SS_1	SPI_1		I
 * PJ[4]		816	0000_0001	SCLK_1	SPI_1		I
 * PJ[1]		815	0000_0001	SIN_1	SPI_1		I
 * PH[15]			0000_0001	SOUT_1	SPI_1		O
 */
#define SPI_1_SS	PJ2	//PJ2_AG_SPI1_CS
#define SPI_1_SCLK	PJ4	//PJ4_AG_SPI1_CLK
#define SPI_1_SIN	PJ1	//PJ1_AG_SPI1_SI
#define SPI_1_SOUT	PH15//PH15_AG_SPI1_SO

void ports_init_spi_1(void)
{
	SIUL2.MSCR[SPI_1_SS].B.IBE = 1;
	SIUL2.IMCR[817 - 512].B.SSS = 2;

	SIUL2.MSCR[SPI_1_SCLK].B.IBE = 1;
	SIUL2.IMCR[816 - 512].B.SSS = 1;

	SIUL2.MSCR[SPI_1_SIN].B.IBE = 1;
	SIUL2.IMCR[815 - 512].B.SSS = 1;

	SIUL2.MSCR[SPI_1_SOUT].B.OBE = 1;
	SIUL2.MSCR[SPI_1_SOUT].B.SSS = 1;
	SIUL2.MSCR[SPI_1_SOUT].B.SRC = 3;
}

void spis_init_SPI_1(void)
{
	SPI_1.MCR.R = 0x00000001;
	SPI_2.MCR.R = 0x00010001;
	SPI_1.MODE.CTAR[0].R = SPI_FMSZ(7) | SPI_CPOL(0) | SPI_CPHA(0);

	SPI_1.MCR.B.HALT = 0x0;
}

/*
 * PI[6]		820	0000_0010	SS_2	SPI_2		I
 * PE[15]		819	0000_0001	SCLK_2	SPI_2		I
 * PG[14]		818	0000_0001	SIN_2	SPI_2		I
 * PG[15]			0000_0010	SOUT_2	SPI_2		O
 */
#define SPI_2_SS	PI6		//PI6_AP_SPI2_CS
#define SPI_2_SCLK	PE15	//PE15_AP_SPI2_CLK
#define SPI_2_SIN	PG14	//PG14_AP_SPI2_SI
#define SPI_2_SOUT	PG15	//PG15_AP_SPI2_SO

void ports_init_spi_2(void)
{
	SIUL2.MSCR[SPI_2_SS].B.IBE = 1;
	SIUL2.IMCR[820 - 512].B.SSS = 2;

	SIUL2.MSCR[SPI_2_SCLK].B.IBE = 1;
	SIUL2.IMCR[819 - 512].B.SSS = 1;

	SIUL2.MSCR[SPI_2_SIN].B.IBE = 1;
	SIUL2.IMCR[818 - 512].B.SSS = 1;

	SIUL2.MSCR[SPI_2_SOUT].B.OBE = 1;
	SIUL2.MSCR[SPI_2_SOUT].B.SSS = 2;
	SIUL2.MSCR[SPI_2_SOUT].B.SRC = 3;
}

void spis_init_SPI_2(void)
{
	SPI_2.MCR.R = 0x00000001;
	SPI_2.MCR.R = 0x00010001;
	SPI_2.MODE.CTAR[0].R = SPI_FMSZ(7) | SPI_CPOL(0) | SPI_CPHA(0);

	SPI_2.MCR.B.HALT = 0x0;
}
